from io import BytesIO

from django.http import JsonResponse
from django.shortcuts import render,redirect,HttpResponse
from firstplan.mine.myform import Admin,AdminReset,Login
from firstplan import models
from firstplan.mine.myimg import check_code


def login(request):
    """登录"""

    # 判断用户是否已经登录，若登录了，继续往下走，若没有登录，返回登录页面【中间件】

    if request.method == "GET":
        form = Login()
        return render(request,'login.html',{"form":form})
    form = Login(data=request.POST)
    if form.is_valid():
        # 获取浏览器表单上的所有字段【字典形式】：form.cleaned_data
        # 浏览器表单上输入的图片验证码与保存在session中的验证码校验，不一致则返回错误信息
        code_str = form.cleaned_data.pop("code_str")
        session_code = request.session.get("image_code")
        if code_str.upper() != session_code.upper():
            form.add_error("code_str","图片验证码输入错误")
            return render(request, 'login.html', {"form": form})

        # 浏览器表单上的用户名和密码与数据库中的数据校验，没有则返回None
        data_login = models.Admin.objects.filter(**form.cleaned_data).first()
        if not data_login:
            # 手动添加错误提示
            form.add_error("password","用户名或密码错误")
            return render(request,'login.html',{"form":form})

        # 用户名和密码正确，则浏览器生成随机字符串，记录在用户cookie中，并写入到session中：id、用户名、图片验证码
        request.session["info"] = {"id":data_login.id,"username":data_login.username}
        request.session.set_expiry(60*60*24*7)
        return redirect('/user/list/')
    print("验证没通过")
    return render(request,'login.html',{"form":form})


def logout(request):
    """注销"""
    request.session.clear()
    return redirect('/login/')


def login_image(request):
    """在登录页面，显示生成的随机图片验证码"""
    img,code_str = check_code()

    # 将图片验证码写入session中，登录时进行校验
    request.session["image_code"] = code_str
    # 给图片验证码设置超时，仅在60秒内有效
    request.session.set_expiry(60)

    # 将图片保存到缓存中，浏览器从缓存中获取图片
    stream = BytesIO()
    img.save(stream,"png")
    return HttpResponse(stream.getvalue())


def forget_pwd(request):
    """密码重置"""
    title = "忘记密码，重置密码"
    if request.method == "GET":
        form = Admin()
        return render(request, 'add_or_edit.html', {"form": form, "title": title})
    form = Admin(data=request.POST)
    if form.is_valid():
        if models.Admin.objects.filter(username=form.cleaned_data['username']):
            models.Admin.objects.filter(username=form.cleaned_data['username']).update(password=form.cleaned_data['password'])
            return redirect('/user/list/')
        else:
            return HttpResponse("该用户不存在，请注册。")
    return render(request, 'add_or_edit.html', {"form": form, "title": title})

    # row_obj = models.Admin.objects.filter(id=nid).first()
    # title = "admin_reset"
    # if not row_obj:
    #     return redirect('/user/list/')
    # if request.method == "GET":
    #     form = AdminReset(instance=row_obj)
    #     return render(request,'add_or_edit.html',{"form":form,"title":title})
    # form = AdminReset(data=request.POST,instance=row_obj)
    # if form.is_valid():
    #     form.save()
    #     if form.instance.pk == request.session["info"]["id"]:
    #         return redirect('/logout')
    #     return redirect('/user/list/')
    # return render(request,'add_or_edit.html',{"form":form,"title":title})


def user_list(request):
    """管理员列表"""
    title = "admin_list"
    # 输入框搜索功能
    data_dict = {}
    search_data = request.GET.get("q","")
    if search_data:
        data_dict["username__contains"] = search_data
    items = models.Admin.objects.filter(**data_dict)

    form = Admin()
    context = {
        "items":items,
        "title": title,
        "form": form,
        "search_data":search_data,
    }
    return render(request,'user_list.html',context)


def user_add(request):
    """注册"""
    title = "注册"
    if request.method == "GET":
        form = Admin()
        return render(request,'add_or_edit.html',{"form":form,"title":title})
    form = Admin(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request,'add_or_edit.html',{"form":form,"title":title})

def user_detail(request):
    """计划详情"""
    id = request.GET.get("uid")
    row_obj = models.Admin.objects.filter(id=id).values("username","password").first()
    if not row_obj:
        return JsonResponse({"status": False, 'tips': "数据不存在"})
    return JsonResponse({"status": True, 'data': row_obj})

def user_edit(request):
        """修改管理员"""
        title = "用户修改"
        id = request.GET.get("uid")
        row_obj = models.Admin.objects.filter(id=id).first()
        if not row_obj:
            return redirect('/user/list/')

        if request.method == "GET":
            form = Admin(instance=row_obj)
            return render(request, 'add_or_edit.html', {"form": form, "title": title})

        form = Admin(data=request.POST, instance=row_obj)
        if form.is_valid():
            form.save()
            if form.instance.pk == request.session["info"]["id"]:
                return redirect('/logout/')
            return redirect('/user/list/')
        return render(request, 'add_or_edit.html', {"form": form, "title": title})

def user_delete(request):
    id = request.GET.get("uid")
    exists = models.Admin.objects.filter(id=id).exists()
    if not exists:
        return JsonResponse({"status": False, "tips": "数据不存在"})
    models.Admin.objects.filter(id=id).delete()
    return JsonResponse({"status": True})